package com.yanqu.road.server.manager.tomb.dao;


import com.fasterxml.jackson.core.type.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.dbV2.serializer.Helper;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.logic.activity.tomb.config.entity.EventInfo;
import com.yanqu.road.server.manager.tomb.Maze;
import com.yanqu.road.server.manager.tomb.entity.DbTombMaze;
import com.yanqu.road.utils.ZipUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TombMazeDaoImpl extends TempDataObjectDao<DbTombMaze> {


    public static TombMazeDaoImpl newInstance() {
        TombMazeDaoImpl dao = new TombMazeDaoImpl();
        return dao;
    }

    public static String updateSql = "update `t_c_activity_tomb_maze` set eliteEventId=?,eliteNpcEvent=?,maze=?,firstIntoUserId=?,generateEventNum=?,brakeBigGripNum=?,exploredBigEventNum=?,exploredNormalEventNum=?,eventInfoList=?,updateTime=? where activityId=? and groupId=? and floor=?";

    @Override
    protected boolean updateData(DbTombMaze data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getCrossDb());
        int i = 1;
        Map<Integer, DbParameter> dbParameterMap = new HashMap<Integer, DbParameter>();
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getEliteEventId()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, data.getEliteNpcEvent()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, ZipUtils.gzip(Helper.toJSONString(data.getMaze()))));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getFirstIntoUserId()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getGenerateEventNum()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getBrakeBigGripNum()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getExploredBigEventNum()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getExploredNormalEventNum()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getEventInfoList())));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));

        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getGroupId()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getFloor()));

        if (getDb().executeNoneQuery(updateSql, dbParameterMap) > 0) {
            return true;
        }
        return false;
    }

    public static String insertSql = "insert into `t_c_activity_tomb_maze`(activityId,groupId,floor,eliteEventId,eliteNpcEvent,maze,firstIntoUserId,generateEventNum,brakeBigGripNum,exploredBigEventNum,exploredNormalEventNum,eventInfoList,createTime,updateTime) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    @Override
    protected boolean addData(DbTombMaze data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getCrossDb());
        int i = 1;
        Map<Integer, DbParameter> dbParameterMap = new HashMap<Integer, DbParameter>();
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getGroupId()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getFloor()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getEliteEventId()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, data.getEliteNpcEvent()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, ZipUtils.gzip(Helper.toJSONString(data.getMaze()))));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getFirstIntoUserId()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getGenerateEventNum()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getBrakeBigGripNum()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getExploredBigEventNum()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getExploredNormalEventNum()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getEventInfoList())));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getCreateTime()));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));
        if (getDb().executeNoneQuery(insertSql, dbParameterMap) > 0) {
            return true;
        }
        return false;
    }


    @Override
    protected DbTombMaze parseData(ResultSet rs) throws SQLException {
        DbTombMaze data = DbTombMaze.newInstance();
        data.setActivityId(rs.getInt("activityId"));
        data.setGroupId(rs.getInt("groupId"));
        data.setFloor(rs.getInt("floor"));
        data.setEliteEventId(rs.getInt("eliteEventId"));
        data.setEliteNpcEvent(rs.getString("eliteNpcEvent"));
        data.setMaze(Helper.toObject(ZipUtils.gunzip(rs.getString("maze")), new TypeReference<Maze>() {
        }));
        data.setFirstIntoUserId(rs.getLong("firstIntoUserId"));
        data.setGenerateEventNum(rs.getInt("generateEventNum"));
        data.setBrakeBigGripNum(rs.getInt("brakeBigGripNum"));
        data.setExploredBigEventNum(rs.getInt("exploredBigEventNum"));
        data.setExploredNormalEventNum(rs.getInt("exploredNormalEventNum"));
        data.setEventInfoList(Helper.toObject(rs.getString("eventInfoList"), new TypeReference<ArrayList<EventInfo>>() {
        }));
        if (data.getEventInfoList() == null) {
            data.setEventInfoList(new ArrayList<>());
        }

        data.setCreateTime(rs.getLong("createTime"));
        data.setUpdateTime(rs.getLong("updateTime"));

        return data;
    }

    public DbTombMaze getData(int activityId, int floor) {
        ResultSet rs = null;
        CallableStatement call = null;
        String selectSql = "select * from t_c_activity_tomb_maze where activityId = ? and floor = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(selectSql);
            call.setInt(1, activityId);
            call.setInt(2, floor);
            rs = call.executeQuery();
            if (rs.next()) {
                return parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public Map<Integer, Map<Integer, DbTombMaze>> getDataMap(int activityId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, DbTombMaze>> dataMap = new ConcurrentHashMap<>();
        String selectSql = "select * from t_c_activity_tomb_maze where activityId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(selectSql);
            call.setInt(1, activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                DbTombMaze data = parse(rs);
                if(!dataMap.containsKey(data.getGroupId())){
                    dataMap.put(data.getGroupId(), new ConcurrentHashMap<>());
                }
                dataMap.get(data.getGroupId()).put(data.getFloor(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public boolean saveData(DbTombMaze data) {
        if (data.isUpdateOption()) {
            if (data.isNeedInsert()) {
                if (addData(data)) {
                    data.setNeedInsert(false);
                }
            } else {
                data.setUpdateTime(System.currentTimeMillis());
                update(data);
            }
        }
        return true;
    }

}
